<template>
  <el-dialog
    :class="fullscreen ? 't-dialog--fullscreen' : 't-dialog'"
    :fullscreen="fullscreen"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    class="view-dialog"
    width="75%"
    :show-close="false"
    :style="{ top: fullscreen ? '0' : '20px' }"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="t__dialog__header">
        <span
          class="el-dialog__title"
          :id="titleId"
          :class="titleClass"
        >
          {{ dialogTitle }}
        </span>
        <div class="t__dialog__menu">
          <el-icon :size="25">
            <i
              class="iconfont el-dialog__close"
              :class="fullscreen ? 'icon-tuichuquanping' : 'icon-fullscreen'"
              @click="handleFullScreen"
            />
          </el-icon>

          <el-icon
            class="el-icon--left"
            @click="close"
            :size="18"
          >
            <ele-Close />
          </el-icon>
        </div>
      </div>
    </template>

    <div class="dialog-form">
      <div class="left">
        <div class="toolbar">
          <el-button
            text
            type="primary"
            icon="ele-Printer"
            v-if="checkBtnPerms('print')"
            v-print="printForm"
            size="default"
          >
            {{ $t("form.data.printData") }}
          </el-button>

          <print-template-list
            v-if="checkBtnPerms('print')"
            :data-ids="[currentFormModel?.id]"
            ref="printTemplateListRef"
          ></print-template-list>

          <print-poster-list
            v-if="checkBtnPerms('print')"
            :data-ids="[currentFormModel?.id]"
            ref="printPosterListRef"
          ></print-poster-list>
          <el-button
            text
            type="primary"
            size="default"
            icon="ele-Share"
            @click="handleShowDataShare"
          >
            {{ $t("form.data.shareData") }}
          </el-button>
          <el-button
            v-if="isEditMode"
            type="primary"
            size="default"
            icon="ele-Check"
            @click="handleUpdate"
          >
            {{ $t("form.viewOrUpdate.confirm") }}
          </el-button>
          <el-button
            v-if="isEditMode"
            size="default"
            bg
            text
            icon="ele-Close"
            @click="handleCancel"
          >
            {{ $t("form.viewOrUpdate.cancel") }}
          </el-button>
          <el-button
            v-if="!isEditMode && canUpdate"
            icon="ele-Edit"
            text
            size="default"
            type="primary"
            @click="handleEditMode"
          >
            {{ $t("form.viewOrUpdate.modify") }}
          </el-button>
          <el-button
            v-if="openReply"
            text
            size="default"
            type="primary"
            icon="ele-ChatLineSquare"
            @click="emit('openReply')"
          >
            {{ $t("form.viewOrUpdate.reply") }}
          </el-button>
          <el-button
            v-if="checkBtnPerms('delete')"
            type="danger"
            text
            size="default"
            icon="ele-Delete"
            @click="handleDelete"
          >
            {{ $t("form.viewOrUpdate.delete") }}
          </el-button>
          <div class="page-wrap">
            <el-icon @click="handlePageChange(-1)">
              <ele-ArrowLeft />
            </el-icon>
            {{ currentDataIndex }}/{{ dataList.length }}
            <el-icon @click="handlePageChange(1)">
              <ele-ArrowRight />
            </el-icon>
          </div>
        </div>
        <div class="form-content">
          <generate-form
            v-if="formConf.fields.length && currentFormModel && isEditMode"
            ref="generateFormRef"
            :form-conf="formConf"
            :page-form-model="currentFormModel"
            :show-hidden-field="true"
            style="margin-bottom: 40px"
          />
          <div v-else>
            <exam-result
              v-if="formType === 4 && dialogVisible"
              id="printForm"
              ref="examFormRef"
              :key="formParseKey"
              :data-id="currentFormModel['id']"
              style="margin-bottom: 40px"
              :show-dimension-report="!!dimensionConfig"
            />
            <view-data
              v-else
              id="printForm"
              v-model:is-print="isPrint"
              :fields="fields"
              :page-form-model="currentFormModel"
            />
          </div>
        </div>
      </div>
      <div class="right">
        <el-tabs v-model="activeName">
          <el-tab-pane
            :label="$t('form.viewOrUpdate.basicInformation')"
            name="info"
          >
            <el-scrollbar style="height: 800px">
              <el-descriptions
                :column="1"
                size="small"
                :title="$t('form.viewOrUpdate.basicInformation')"
              >
                <el-descriptions-item
                  v-for="field in fixedFields"
                  :key="field.value"
                  :label="field.label"
                >
                  <span v-if="field.value === 'submitUaOs'">
                    {{ currentFormModel.submitUa ? currentFormModel.submitUa.os.name : "" }}
                    {{ currentFormModel.submitUa ? currentFormModel.submitUa.os.version : "" }}
                  </span>
                  <span v-if="field.value === 'submitBrowser'">
                    {{ currentFormModel.submitUa ? currentFormModel.submitUa.browser.name : "" }}
                    {{ currentFormModel.submitUa ? currentFormModel.submitUa.browser.version : "" }}
                  </span>
                  <span v-if="field.value === 'submitUaDevice'">
                    {{ currentFormModel.submitUa ? currentFormModel.submitUa.device : "" }}
                  </span>
                  <span v-if="field.value === 'wxUserInfo'">
                    {{ currentFormModel.wxUserInfo ? currentFormModel.wxUserInfo.nickname : "" }}
                  </span>
                  <span v-else>
                    {{ currentFormModel[field.value] }}
                  </span>
                </el-descriptions-item>
              </el-descriptions>
              <data-remark
                :data-id="currentFormModel?.id"
                :form-key="formKey"
              />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane
            :label="$t('form.data.updateInfo')"
            name="update"
          >
            <data-logs
              :id="currentFormModel?.id"
              v-if="dialogVisible"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <data-share ref="dataShareRef" />
  </el-dialog>
</template>

<script name="ViewOrUpdate" setup>
import { defineProps, inject, onBeforeMount, ref, watch } from "vue";
import { updateFormDataDeletedRequest, updateFormDataRequest } from "@/api/project/data";
import { getSettingRequest } from "@/api/project/setting";
import { jsonSimpleClone, removeHtmlTag } from "@/views/formgen/utils";
import { i18n } from "@/i18n";
import print from "vue3-print-nb";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";
import { ElMessageBox } from "element-plus";
import { useFormInfo } from "@/stores/formInfo";
import GenerateForm from "@/views/formgen/components/GenerateForm/GenerateForm.vue";
import ExamResult from "@/views/form/exam/ExamResult.vue";
import ViewData from "./ViewData.vue";
const PrintPosterList = loadAsyncComponent(() => import("./table/PrintPosterList.vue"));
const PrintTemplateList = loadAsyncComponent(() => import("./table/PrintTemplateList.vue"));

const DataRemark = loadAsyncComponent(() => import("./components/DataRemark.vue"));
const DataShare = loadAsyncComponent(() => import("./components/DataShare.vue"));
const DataLogs = loadAsyncComponent(() => import("./components/DataLogs.vue"));

import { storeToRefs } from "pinia";
import { loadAsyncComponent } from "@/utils/asyncComponent";

const props = defineProps({
  fields: {
    type: Array,
    default: () => []
  },
  fixedFields: {
    type: Array,
    default: () => []
  },
  formKey: {
    type: String,
    default: ""
  },
  canUpdate: {
    type: Boolean,
    default: false
  }
});

const vPrint = print;
const activeName = ref("info");
const isEditMode = ref(false);
const formParseKey = ref(new Date().getTime());
const currentFormModel = ref(null);

const formConf = ref({
  formRef: "generateForm",
  fields: [],
  formKey: "",
  disabled: true,
  span: 24,
  size: "default",
  labelPosition: "top",
  labelWidth: 100,
  formRules: "rules",
  gutter: 15,
  formBtns: false,
  resetBtn: false,
  theme: {
    backgroundImg: "",
    showFormTitle: true,
    showFormDescribe: true,
    showFormNumber: false,
    btnsColor: null
  }
});

const dialogVisible = ref(false);
const dialogTitle = ref(i18n.global.t("form.viewOrUpdate.view"));
const fullscreen = ref(false);
const openReply = ref(false);
const isPrint = ref(false);
const remarkEditDisable = ref(false);
const remarkButton = ref("");

const printForm = ref({
  id: "printForm",
  popTitle: "",
  extraHead:
    '<meta http-equiv="Content-Language" content="zh-cn"/>,<style>  #printForm { width: 100%;  }  .not-print {display: none!important } .print{ display: block!important}<style>',
  previewBeforeOpenCallback(vue) {
    //console.log("正在加载预览窗口");
  },
  previewOpenCallback(vue) {
    //console.log("已经加载完预览窗口");
  },
  beforeOpenCallback(vue) {
    //console.log("打开之前");
  },
  openCallback(vue) {
    //console.log("执行了打印");
  },
  closeCallback(vue) {
    //console.log("关闭了打印工具");
  }
});

watch(
  () => props.fields,
  val => {
    formConf.value.fields = val
      .filter(item => {
        return item.scheme;
      })
      .map(item => {
        if (item.scheme) {
          item.scheme.viewMode = true;
          // 去除标签中富文本
          item.scheme.config.label = removeHtmlTag(item.scheme.config.label);
        }
        return item.scheme;
      });
  },
  { deep: true, immediate: true }
);

onBeforeMount(() => {
  queryUserProjectSetting();
});

const checkBtnPermsFunc = inject("checkBtnPerms");

const checkBtnPerms = btn => {
  return checkBtnPermsFunc(btn);
};

// 维度
const dimensionConfig = inject("dimensionConfig");

// 全部数据列表1
const dataList = ref([]);
const currentDataIndex = ref(1);

const handlePageChange = num => {
  if (currentDataIndex.value === 1 && num === -1) {
    return;
  }
  if (currentDataIndex.value === dataList.value.length && num === 1) {
    return;
  }
  currentDataIndex.value = currentDataIndex.value + num;
  currentFormModel.value = jsonSimpleClone(dataList.value[currentDataIndex.value - 1]);
  isEditMode.value = false;
  initDialog();
};

const showDialog = (formModel, tableList) => {
  currentFormModel.value = jsonSimpleClone(formModel);
  initDialog();
  dataList.value = tableList;
  currentDataIndex.value = tableList.findIndex(item => item.id === formModel?.id) + 1;
};

const initDialog = () => {
  formConf.value.disabled = true;
  dialogTitle.value = i18n.global.t("form.viewOrUpdate.view");
  formParseKey.value = new Date().getTime();
  isEditMode.value = false;
  dialogVisible.value = true;
  remarkEditDisable.value = true;
  remarkButton.value = i18n.global.t("form.viewOrUpdate.edit");
  activeName.value = "info";
};

const emit = defineEmits(["reload", "openReply"]);

const handleCancel = () => {
  if (isEditMode.value) {
    isEditMode.value = false;
    formConf.value.disabled = true;
    return;
  }
  dialogVisible.value = false;
  emit("reload");
};

const handleEditMode = () => {
  isEditMode.value = true;
  dialogTitle.value = i18n.global.t("form.viewOrUpdate.edit");
  formConf.value.disabled = false;
};

const handleFullScreen = () => {
  fullscreen.value = !fullscreen.value;
};

const queryUserProjectSetting = () => {
  getSettingRequest(props.formKey).then(res => {
    if (res.data) {
      openReply.value = res.data.openReply;
    }
  });
};

const dataShareRef = ref(null);

const handleShowDataShare = () => {
  dataShareRef.value.show(currentFormModel.value?.id, currentFormModel.value?.dataId, props.fields);
};

const handleDelete = () => {
  ElMessageBox.alert(i18n.global.t("form.viewOrUpdate.irreversibleDeletion"), i18n.global.t("formI18n.all.waring"), {
    confirmButtonText: i18n.global.t("formI18n.all.confirm"),
    callback: action => {
      if (action === "confirm")
        updateFormDataDeletedRequest(props.formKey, [currentFormModel.value?.id], true).then(res => {
          MessageUtil.success(i18n.global.t("formI18n.all.success"));
          dialogVisible.value = false;
          emit("reload");
        });
    }
  });
};

const generateFormRef = ref(null);

const updateFromRequest = () => {
  let formModel = jsonSimpleClone(generateFormRef.value.formModel);
  let tempFormModel = {};
  for (let key in formModel) {
    let bool = /.*\d+.*/g.test(key);
    if (bool) {
      tempFormModel[key] = formModel[key];
    }
  }
  updateFormDataRequest({
    id: currentFormModel.value?.id,
    completeTime: null,
    formKey: props.formKey,
    submitOs: "",
    submitBrowser: "",
    submitUa: null,
    wxUserInfo: null,
    wxOpenId: "",
    originalData: tempFormModel
  }).then(() => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    dialogVisible.value = false;
    setTimeout(() => {
      emit("reload");
    }, 1000);
  });
};

const handleUpdate = () => {
  generateFormRef.value.validateForm().then(valid => {
    if (valid) {
      updateFromRequest();
    } else {
      MessageBoxUtil.confirm(
        i18n.global.t("form.viewOrUpdate.forceSaveText"),
        () => {
          updateFromRequest();
        },
        i18n.global.t("form.viewOrUpdate.confirm")
      );
    }
  });
};

const { formType } = storeToRefs(useFormInfo());

defineExpose({
  showDialog
});
</script>

<style lang="scss" scoped>
.view-dialog {
  height: 100%;
}
.dialog-form {
  height: 80vh;
  display: flex;
  margin-top: 5px;
  justify-content: center;

  .left {
    height: 100%;
    width: 75%;
  }
  .form-content {
    height: 100%;
    width: 100%;
    overflow: auto;
  }

  .form-content {
    overflow-y: auto;
  }

  .toolbar {
    display: flex;
    margin-bottom: 10px;
    margin-top: 5px;
    flex-wrap: wrap;
    .el-icon {
      color: var(--el-color-primary);
      cursor: pointer;
    }
    .page-wrap {
      user-select: none;
      margin-left: auto;
      display: flex;
      align-items: center;
      .el-icon {
        margin: 0 10px;
      }
    }
  }

  .right {
    height: 100%;
    width: 25%;
    overflow-y: scroll;
    padding-left: 10px;
  }
}

.el-icon--left :hover {
  cursor: pointer;
  transition: transform 0.2s ease-in-out;
  transform: rotate(180deg);
}

.el-icon--left :not(:hover) {
  transition: transform 0.3s ease; /* 添加过渡效果，使旋转平滑 */
  transform: rotate(0deg); /* 鼠标离开后缓慢转回原始状态 */
}

.operate-btns {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.exam-result-wrap .exam-result-wrap__card) {
  width: 90% !important;
}

:deep(.exam-result-wrap) {
  height: 100%;
  overflow: inherit !important;
}
.t__dialog__header {
  margin-top: 10px;
  .el-dialog__title {
    margin-left: 20px;
  }
}
</style>
<style lang="scss">
.view-dialog {
  --el-dialog-padding-primary: 0;
}
</style>
